import { memo } from 'react'
import { componentGroupList } from '@/components/QuestionComponents'
import { Typography } from 'antd'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import { addComponent } from '@/store/modules/componentsReducer'
import { ComponentConfType } from '@/components/QuestionComponents'
import { nanoid } from 'nanoid'

const { Title } = Typography

const ComponentLib = memo(() => {
  const dispatch = useDispatch()

  const getComponent = (c: ComponentConfType, index: number) => {
    const { title, type, component: Component, defaultProps } = c

    const handleClick = () => {
      dispatch(
        addComponent({
          fe_id: nanoid(),
          type,
          title,
          props: defaultProps,
        })
      )
    }

    return (
      <div key={index} className={styles.wrapper} onClick={handleClick}>
        <div className={styles.component}>
          <Component />
        </div>
      </div>
    )
  }

  return (
    <>
      {componentGroupList.map((item, index) => {
        return (
          <div key={index}>
            <Title level={3} style={{ fontSize: '16px', marginTop: index > 0 ? '20px' : 0 }}>
              {item.group}
            </Title>
            <div>
              {item.components.map((item, index) => {
                return getComponent(item, index)
              })}
            </div>
          </div>
        )
      })}
    </>
  )
})

export default ComponentLib
